package com.it.gw.modules.water.activity.pump

import ADNMVo
import android.annotation.SuppressLint
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.Toast
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.it.common.bean.MapDataBean
import com.it.common.utils.DisplayUtil
import com.it.common.utils.GsonUtils
import com.it.common.utils.RvSpacesItemUtils
import com.it.common.utils.isNotEmpty
import com.it.data.network.req.PumpRecordDto
import com.it.data.network.rsp.DictionariesVo
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.databinding.ActivityPumpItemsBinding
import com.it.gw.databinding.LayoutPopAddvcdSelectBinding
import com.it.gw.databinding.LayoutPopSingleSelectBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.manager.DictionariesManager
import com.it.gw.modules.map.activity.MapActivity
import com.it.gw.modules.water.adapter.ADDVCDAdapter
import com.it.gw.modules.water.adapter.PumpItemAdapter
import com.it.gw.modules.water.adapter.SelectTypeAdapter
import com.it.gw.modules.water.viewmodel.WaterViewModel

//泵站列表
class PumpItemsActivity : BaseActivity<ActivityPumpItemsBinding>() {
    private val waterViewModel by viewModels<WaterViewModel>()

    companion object {
        const val PAGE_SIZE = 20
        const val TAG = "PumpItemsActivity"
    }

    private var pageNum = 1
    private val datas by lazy { mutableListOf<PumpRecordDto>() }
    private val adapter by lazy {
        PumpItemAdapter(context = this, datas = datas, listener = {
            val intent = Intent(this, PumpItemDetailActivity::class.java)
            intent.putExtra("title", it?.pustName)
            intent.putExtra("id", it!!.pustCode)
            startActivity(intent)
        })
    }


    override fun initObserver() {

        waterViewModel.pumpRecordDtoListLiveData.observe(this) {
            loadMoreData = false
            ProgressDialog.hide()
            Log.d(TAG, "initObserver: ${it.data?.list}")
            binding.swipeRefreshLayout.isRefreshing = false
            if (it.result) {
                if (it.data?.list.isNullOrEmpty()) {
                    if (pageNum > 1) {
                        pageNum--
                        Toast.makeText(this, "没有更多数据了！", Toast.LENGTH_SHORT).show()
                    } else {
                        //第一次就没数据
                        datas.clear()
                        adapter.notifyDataSetChanged()
//                    llNoData.setVisibility(View.VISIBLE);
//                    srHasData.setVisibility(View.GONE);
                    }

                } else {
//                llNoData.setVisibility(View.GONE);
//                srHasData.setVisibility(View.VISIBLE);
                    if (pageNum == 1) {
                        datas.clear()
                    }
                    datas.addAll(it.data!!.list!!)
                    Log.d(TAG, "initObserver: pageGQStationVoListLiveData ${datas}")
                    adapter.notifyDataSetChanged()

                }
            } else {
                Toast.makeText(this, it.msg, Toast.LENGTH_SHORT).show()
            }


        }


    }

    override fun initListener() {
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.searchContent.text = null
            dictionariesVo = null
            adnmShiVo = null
            adnmTuanVo = null
            setSKLXView()
            setXZQHView()
            pageNum = 1
            getData()
        }
        binding.rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 获取布局管理器
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager

                // 获取最后一个可见的 item 的位置
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()

                // 获取总的 item 数量
                val totalItemCount = layoutManager.itemCount

                // 判断是否滑动到了底部
                if (totalItemCount >= PAGE_SIZE && lastVisibleItemPosition == totalItemCount - 1) {
                    // 滑动到了底部，执行相关操作
                    loadMoreData()
                }
            }
        })
        binding.rlSklx.setOnClickListener {
            ProgressDialog.show(this)
            mainViewModel.wellUseType(type = "PUST_TYPE", resp = {
                ProgressDialog.hide()
                Log.d(TAG, "wellUseType: ${it.data}")
                if (it.data.isNotEmpty()) {
                    showSelectPopupWindow(binding.rlTop, list = it.data!!)
                }

            })

        }
        binding.rlXzqh.setOnClickListener {
            ProgressDialog.show(this)
            mainViewModel.getShiAddvcd(resp = {
                ProgressDialog.hide()
                Log.d(TAG, "getShiAddvcd: ${it.data}")
                if (it.data.isNotEmpty()) {
                    showSelectShiTuanPopupWindow(binding.rlTop, shiList = it.data!!)
                }

            })
        }
        binding.tvMap.setOnClickListener {
            val intent = Intent(this, MapActivity::class.java)
            intent.putExtra("title", resources.getString(R.string.str_pum_items))
            val mapList =
                datas.filter {
                    it.pustName.isNotEmpty()
                            && it.lgtd.isNotEmpty()
                            && it.lttd.isNotEmpty()
                }
                    .map { MapDataBean(name = it.pustName, lgtd = it.lgtd, lttd = it.lttd) }
                    .toMutableList()
            intent.putExtra(MapActivity.MAP_DATA, GsonUtils.objToJsonStr(mapList))
            startActivity(intent)
        }
        binding.tvSearch.setOnClickListener {
            ProgressDialog.show(this)
            pageNum = 1
            getData()

        }

    }


    override fun initData() {
        ProgressDialog.show(this)
        getData()
    }

    private var loadMoreData = false;
    private fun loadMoreData() {
        if(loadMoreData){
            return
        }
        Log.d(TAG, "loadMoreData: ")
        pageNum += 1
        loadMoreData = true;
        getData()
    }
    private fun getData() {
        waterViewModel.getPumpItems(
            pageNum = pageNum,
            pageSize = PAGE_SIZE,
            pustType = dictionariesVo?.ITEMCODE,
            name = binding.searchContent.text.toString(),
            addvcd = getVo()?.ADDVCD

        )
    }
    private fun getVo(): ADNMVo? {
        if(adnmTuanVo!=null){
            return adnmTuanVo;
        }
        return adnmShiVo

    }

    override fun initView() {
        setTitle(
            title = R.string.str_pum_items,
            isBack = true

        )
        DictionariesManager.getBengZhanDictionaries()
        val map = hashMapOf(RvSpacesItemUtils.BOTTOM_DECORATION to DisplayUtil.dip2px(this, 1f))
        binding.rvList.addItemDecoration(RvSpacesItemUtils(map))
        binding.rvList.adapter = adapter


    }

    override fun setContentView() {
        binding = ActivityPumpItemsBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    private var selectBinding: LayoutPopSingleSelectBinding? = null
    private var dictionariesVo: DictionariesVo? = null

    /**
     * 筛选弹窗
     * @param anchor View
     */
    private fun showSelectPopupWindow(anchor: View, list: List<DictionariesVo>) {
        selectBinding = LayoutPopSingleSelectBinding.inflate(layoutInflater)
// 创建 PopupWindow
        val popupWindow = PopupWindow(
            selectBinding?.root,
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val map = HashMap<String, Int>()
        //间距
        map[RvSpacesItemUtils.BOTTOM_DECORATION] = 1
        selectBinding?.rvList?.addItemDecoration(RvSpacesItemUtils(map))
        val selectTypeAdapter = SelectTypeAdapter(datas = list, context = this, listener = {

            popupWindow.dismiss()
            dictionariesVo = it
            Log.d(TAG, "showSelectPopupWindow: ${dictionariesVo}")
            setSKLXView()
            pageNum = 1
            getData()
        })
        selectBinding?.rvList?.adapter = selectTypeAdapter

        // 设置 PopupWindow 的其他属性
        popupWindow.isFocusable = true
        selectBinding?.vOutSide?.setOnClickListener {
            popupWindow.dismiss()
        }
        selectBinding?.rlCancel?.setOnClickListener {
            popupWindow.dismiss()
        }

        // 显示 PopupWindow
        popupWindow.showAsDropDown(anchor)

    }

    private lateinit var shiAdapter: ADDVCDAdapter
    private lateinit var tuanAdapter: ADDVCDAdapter
    private lateinit var addvcdSelectBinding: LayoutPopAddvcdSelectBinding
    private val tuanList = mutableListOf<ADNMVo>()
    private fun showSelectShiTuanPopupWindow(anchor: View, shiList: List<ADNMVo>) {
        adnmTuanVo = null
        adnmShiVo = null
        addvcdSelectBinding = LayoutPopAddvcdSelectBinding.inflate(layoutInflater)
        val popupWindow = PopupWindow(
            addvcdSelectBinding.root,
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val map = HashMap<String, Int>()
        //间距
        map[RvSpacesItemUtils.BOTTOM_DECORATION] = 1
        addvcdSelectBinding.rvShi.addItemDecoration(RvSpacesItemUtils(map))
        shiList[0].selected = true
        selectShi(shiList[0])
        shiAdapter = ADDVCDAdapter(datas = shiList, context = this, listener = {
            for (i in shiList.indices) {
                if (shiList[i].ADDVCD == it.ADDVCD) {
                    shiList[i].selected = true
                    selectShi(it)
                } else {
                    shiList[i].selected = false
                }
            }
            shiAdapter.notifyDataSetChanged()

        })
        addvcdSelectBinding.rvShi.adapter = shiAdapter
        //团
        addvcdSelectBinding.rvTuan.addItemDecoration(RvSpacesItemUtils(map))
        tuanAdapter = ADDVCDAdapter(datas = tuanList, context = this, listener = {
            for (i in tuanList.indices) {
                if (tuanList[i].ADDVCD == it.ADDVCD) {
                    tuanList[i].selected = true
                    selectTuan(it)

                } else {
                    tuanList[i].selected = false
                }
            }
            // popupWindow.dismiss()
            tuanAdapter.notifyDataSetChanged()

        })
        addvcdSelectBinding.rvTuan.adapter = tuanAdapter


        // 设置 PopupWindow 的其他属性
        popupWindow.isFocusable = true
        addvcdSelectBinding?.vOutSide?.setOnClickListener {
            popupWindow.dismiss()
        }
        addvcdSelectBinding?.rlCancel?.setOnClickListener {
            popupWindow.dismiss()
        }

        addvcdSelectBinding?.rlOk?.setOnClickListener {
            setXZQHView()
            popupWindow.dismiss()
            pageNum = 1
            getData()

        }


        // 显示 PopupWindow
        popupWindow.showAsDropDown(anchor)

    }

    private var adnmTuanVo: ADNMVo? = null
    private fun selectTuan(vo: ADNMVo) {
        adnmTuanVo = vo

    }

    private var adnmShiVo: ADNMVo? = null
    private fun selectShi(vo: ADNMVo) {
        adnmShiVo = vo
        ProgressDialog.show(this)
        mainViewModel.getTuanAddvcd(id = vo.ADDVCD, resp = {
            ProgressDialog.hide()
            Log.d(TAG, "getTuanAddvcd: ${it.data}")
            if (it.data.isNotEmpty()) {
                tuanList.clear()
                tuanList.addAll(it.data!!)
                //   tuanList.get(0).selected = true
                tuanAdapter.notifyDataSetChanged()
            }


        })

    }

    //设置水库类型选择
    private fun setSKLXView() {
        if (!dictionariesVo.isNotEmpty()) {
            binding.tvSklx.text = "水闸类型"
        } else {
            binding.tvSklx.text = dictionariesVo!!.ITEMNAME
        }

    }

    @SuppressLint("SetTextI18n")
    private fun setXZQHView() {
        if (adnmTuanVo.isNotEmpty()) {
            binding.tvXzqh.text = "${adnmShiVo?.ADNM}/${adnmTuanVo?.ADNM}"
        } else {
            if(adnmShiVo.isNotEmpty()){
                binding.tvXzqh.text = "${adnmShiVo?.ADNM}"
            }
            else{
                binding.tvXzqh.text = "行政区划"
            }


        }

    }
}